package src.hash;

import java.util.ArrayList;
import java.util.List;

public class no448 {//找到所有数组中消失的数字
    public static void main(String[] args) {
        int[] arr = {4,3,2,7,8,2,3,1};
        System.out.println(findDisappearedNumbers2(arr));
    }

    //数组作哈希表
    public List<Integer> findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        ArrayList<Integer> list = new ArrayList<>();
        int[] hashArray = new int[n + 1];
        for (int i : nums) {
            hashArray[i] = i;
        }
        for (int i = 1; i <= n; i++) {
            if (hashArray[i] == 0) {
                list.add(i);
            }
        }
        return list;

    }

    //原地哈希，交换元素
    public static List<Integer> findDisappearedNumbers2(int[] nums) {
        int n = nums.length;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            while (nums[nums[i] - 1] != nums[i]) {  //注意这里是while不是if
                swap(nums, i, nums[i] - 1);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] != i + 1) {
                list.add(i + 1);
            }
        }
        return list;
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
